package com.huazhi.wzsnw.util.tcp;

import com.huazhi.wzsnw.mapper.AlertMapper;
import com.huazhi.wzsnw.mapper.AlertValueMapper;
import com.huazhi.wzsnw.mapper.LinedMapper;
import com.huazhi.wzsnw.mapper.LinedStateMapper;
import com.huazhi.wzsnw.model.Alert;
import com.huazhi.wzsnw.model.AlertValue;
import com.huazhi.wzsnw.model.Lined;
import com.huazhi.wzsnw.model.LinedState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class Server {
    //保存所有的连接
    private HashSet<User> users;
    //线程标识
    private boolean run = true;

//     static Map<String, Lined> alertNumber = new HashMap<String, Lined>();
//     static Map<String, List<Alert>> alert = new HashMap<String, List<Alert>>();

//    public static Map<String, List<Alert>> getAlert() {
//        return alert;
//    }

//    public static void setAlert(Map<String, List<Alert>> alert) {
//        Server.alert = alert;
//    }

//    public static Map<String, Lined> getAlertNumber() {
//        return alertNumber;
//    }
//
//    public static void setAlertNumber(Map<String, Lined> alertNumber) {
//        Server.alertNumber = alertNumber;
//    }

    LinedMapper linedMapper;
    LinedStateMapper linedStateMapper;
    AlertMapper alertMapper;
    AlertValueMapper alertValueMapper;


    public Server() {
        run = true;
        users = new HashSet<User>();
    }
    //public void start(LinedMapper linedMapper) throws IOException {
    public void start(LinedMapper linedMapper, LinedStateMapper linedStateMapper, AlertMapper alertMapper,AlertValueMapper alertValueMapper) throws IOException {
       this.alertValueMapper =alertValueMapper;
       this.linedMapper =linedMapper;
       this.linedStateMapper = linedStateMapper;
       this.alertMapper = alertMapper;
  try {
      //服务初始化
      ServerSocketChannel serverSocket = ServerSocketChannel.open();
      //设置为非阻塞
      serverSocket.configureBlocking(false);
      //绑定端口
      serverSocket.bind(new InetSocketAddress(8090));
      //注册OP_ACCEPT事件（即监听该事件，如果有客户端发来连接请求，则该键在select()后被选中）
      Selector selector = Selector.open();
      serverSocket.register(selector, SelectionKey.OP_ACCEPT);
      Map<String,String> map = new HashMap<>();
      int i =0;

      while (run) {
          //选择准备好的事件
          selector.select();
          //已选择的键集
          Iterator<SelectionKey> it = selector.selectedKeys().iterator();
          while (it.hasNext()){
              SelectionKey key = it.next();
              //处理掉后将键移除，避免重复消费(因为下次选择后，还在已选择键集中)
              it.remove();
              //处理连接请求
              if (key.isAcceptable()) {
                  //处理请求
                  SocketChannel socket = serverSocket.accept();
                  socket.configureBlocking(false);
                  //注册read，监听客户端发送的消息
                  socket.register(selector, SelectionKey.OP_READ);
                  i++;
                  //keys为所有键，除掉serverSocket注册的键就是已连接socketChannel的数量
                  System.out.println("==========================已有"+i+"个dtu进行连接");
                  //向客户端发送消息

              }
              if (key.isReadable()) {
                  SocketChannel socket = (SocketChannel) key.channel();
                  InetSocketAddress address = (InetSocketAddress) socket.getRemoteAddress();
                  String addressPort = address.getHostString()+address.getPort();
                  ByteBuffer bf = ByteBuffer.allocate(1024 * 4);
                  int len = 0;
                  byte[] res = new byte[1024 * 4];
                  //捕获异常，因为在客户端关闭后会发送FIN报文，会触发read事件，但连接已关闭,此时read()会产生异常
                  try {
                      while ((len = socket.read(bf)) > 0) {
                          bf.flip();
                          bf.get(res, 0, len);
//                                System.out.println(new String(res, 0, len));
                          String s =new String(res,0,len);
                          System.out.println("DTU发送数据进入可读状态+++++++++++++++++++");
                          if(!s.contains("DTU")){
                              if(s.contains("WZSNWV1")){
                                  String bianhao = s.substring(3, 19);
                                  if(map.get(address)==null){
                                      map.put(addressPort,bianhao);
                                  }
                              }else {
                                  String data = bytesToHexString(res);
                                  String jinzhi = data.substring(0, 119);
                                  System.out.println("++++++++++++++++++++++++++++++dtu编号："+map.get(addressPort));
                                  if(map.get(addressPort) != null&&map.get(addressPort).contains("WZSNWV1")){
                                      System.out.println("插入数据");
                                   updateLined(map.get(addressPort),jinzhi);
                                    updateLinedState(map.get(addressPort),jinzhi);
                                    updateAlterValue(map.get(addressPort),jinzhi);
                                    getShuju(map.get(addressPort),jinzhi);
                                  }

                              }
                          }
                          bf.clear();
                      }
                  } catch (IOException e) {
                      //客户端关闭了
                      key.cancel();
                      socket.close();
                  }
              }
          }

      }
  }catch (IOException e){
      e.printStackTrace();
      System.out.println("服务器异常，即将关闭..........");
      System.out.println("=========================================================");
  }
    }

    public void stop() {
        run = false;
    }

    public  static void   getShuju(String number, String jinzhi) throws IOException {

        String chanshuibengState = hexToDecOfString(jinzhi.substring(12, 14) + jinzhi.substring(15, 17));
        String fanxibengState = hexToDecOfString(jinzhi.substring(18, 20) + jinzhi.substring(21, 23));
        String jiaobanjiState = hexToDecOfString(jinzhi.substring(24, 26) + jinzhi.substring(27, 29));
        String gufengji1State = hexToDecOfString(jinzhi.substring(30, 32) + jinzhi.substring(33, 35));
        String gufengji2State = hexToDecOfString(jinzhi.substring(36, 38) + jinzhi.substring(39, 41));
        String jinshuibengState = hexToDecOfString(jinzhi.substring(42, 44) + jinzhi.substring(45, 47));
        String huiliubengState = hexToDecOfString(jinzhi.substring(48, 50) + jinzhi.substring(51, 53));
        int chanshuibengRuntime = hexToDec(jinzhi.substring(54, 56) + jinzhi.substring(57, 59));
        int chanshuibengStoptime = hexToDec(jinzhi.substring(60, 62) + jinzhi.substring(63, 65));
        int fanxibengRuntime = hexToDec(jinzhi.substring(66, 68) + jinzhi.substring(69, 71));
        int fanxibengStoptime = hexToDec(jinzhi.substring(72, 74) + jinzhi.substring(75, 77));
        int gufengjiRuntime = hexToDec(jinzhi.substring(78, 80) + jinzhi.substring(81, 83));
        int gufengjiStoptime = hexToDec(jinzhi.substring(84, 86) + jinzhi.substring(87, 89));
        int jiaobanRuntime = hexToDec(jinzhi.substring(90, 92) + jinzhi.substring(93, 95));
        int jiaobanStoptime = hexToDec(jinzhi.substring(96, 98) + jinzhi.substring(99, 101));
        int huiliubengRuntime = hexToDec(jinzhi.substring(102, 104) + jinzhi.substring(105, 107));
        int huiliubengStoptime = hexToDec(jinzhi.substring(108, 110) + jinzhi.substring(111, 113));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dtuText =dateFormat.format(new Date())+ "产水泵状态"+chanshuibengState+"运行时间"+chanshuibengRuntime+"停止时间"+chanshuibengStoptime+"进水泵状态"+jinshuibengState+"反洗泵状态"+fanxibengState+"运行时间"+fanxibengRuntime+"停止时间"+fanxibengStoptime+
                "搅拌机泵状态"+jiaobanjiState+"运行时间"+jiaobanRuntime+"停止时间"+jiaobanStoptime+"鼓风机泵状态"+gufengji1State+"运行时间"+gufengjiRuntime+"停止时间"+gufengjiStoptime+"回流泵状态"+huiliubengState+"运行时间"+huiliubengRuntime+"停止时间"+huiliubengStoptime;

        String  dirPath =  "C:\\Users\\Administrator\\Desktop\\dtuData";
        String filePath = dirPath +"\\"+number+".txt";
        File dir =  new File(dirPath);

        if(!dir.exists()){
            dir.mkdirs();
        }
        File text = new File(filePath);
        if(!text.exists()){
          text.createNewFile();
        }

        if(text.length()>1024*20){
            FileWriter fileWriter = new FileWriter(text);
          fileWriter.write("");
          fileWriter.flush();
          fileWriter.close();
        }else {
            FileWriter fileWriter = new FileWriter(text,true);
            fileWriter.write("\r\n");
           fileWriter.write(dtuText);
           fileWriter.flush();
           fileWriter.close();
        }
    }

    public void updateLined( String numberBig, String jinzhi) {
        Integer csbYxSj= null;
        Integer csbTzSj = null ;
        Integer fxbTzSj = null ;
        Integer fxbYxSj = null;
        Integer gfjYxSj = null ;
        Integer gfjTzSj = null ;
        Integer jbjYxSj = null ;
        Integer jbjTzSj = null ;
        Integer hlbYxSj = null ;
        Integer hlbTzSj = null ;
        Date date = new Timestamp(System.currentTimeMillis());
        if (numberBig != null&&!"".equals(numberBig)) {
            Lined one = linedMapper.getByDtu(numberBig);
            if (one != null) {
                String chanshuibengState = hexToDecOfString(jinzhi.substring(12, 14) + jinzhi.substring(15, 17));
                String fanxibengState = hexToDecOfString(jinzhi.substring(18, 20) + jinzhi.substring(21, 23));
                String jiaobanjiState = hexToDecOfString(jinzhi.substring(24, 26) + jinzhi.substring(27, 29));
                String gufengji1State = hexToDecOfString(jinzhi.substring(30, 32) + jinzhi.substring(33, 35));
                String gufengji2State = hexToDecOfString(jinzhi.substring(36, 38) + jinzhi.substring(39, 41));
                String jinshuibengState = hexToDecOfString(jinzhi.substring(42, 44) + jinzhi.substring(45, 47));
                String huiliubengState = hexToDecOfString(jinzhi.substring(48, 50) + jinzhi.substring(51, 53));

                int chanshuibengRuntime = hexToDec(jinzhi.substring(54, 56) + jinzhi.substring(57, 59));
                int chanshuibengStoptime = hexToDec(jinzhi.substring(60, 62) + jinzhi.substring(63, 65));
                int fanxibengRuntime = hexToDec(jinzhi.substring(66, 68) + jinzhi.substring(69, 71));
                int fanxibengStoptime = hexToDec(jinzhi.substring(72, 74) + jinzhi.substring(75, 77));
                int gufengjiRuntime = hexToDec(jinzhi.substring(78, 80) + jinzhi.substring(81, 83));
                int gufengjiStoptime = hexToDec(jinzhi.substring(84, 86) + jinzhi.substring(87, 89));
                int jiaobanRuntime = hexToDec(jinzhi.substring(90, 92) + jinzhi.substring(93, 95));
                int jiaobanStoptime = hexToDec(jinzhi.substring(96, 98) + jinzhi.substring(99, 101));
                int huiliubengRuntime = hexToDec(jinzhi.substring(102, 104) + jinzhi.substring(105, 107));
                int huiliubengStoptime = hexToDec(jinzhi.substring(108, 110) + jinzhi.substring(111, 113));

                if (!chanshuibengState.equals(one.getChanshuibeng())) {
                    if("1".equals(one.getChanshuibeng())){
                      csbYxSj = getFen(one.getChanshuibengchangetime(),date);
                    }else {
                        csbTzSj = getFen(one.getChanshuibengchangetime(),date);
                    }
                    one.setChanshuibengchangetime(date);
                }
                if (!fanxibengState.equals(one.getFanxibeng())) {
                    if("1".equals(one.getFanxibeng())){
                        csbYxSj = getFen(one.getChanshuibengchangetime(),date);
                    }else {
                        csbTzSj = getFen(one.getChanshuibengchangetime(),date);
                    }
                    one.setFanxibengchangetime(date);
                }
                if (!jiaobanjiState.equals(one.getJiaobanji())) {
                   if ("1".equals(one.getJiaobanji())){
                       jbjYxSj = getFen(one.getJiaobanjichangetime(),date);
                   }else {
                       jbjTzSj = getFen(one.getJiaobanjichangetime(),date);
                   }
                    one.setJiaobanjichangetime(date);
                }
                if (!gufengji1State.equals(one.getGufengji1())) {
                    if("1".equals(one.getGufengji1())){
                        gfjYxSj = getFen(one.getGufengji1changetime(),date);
                    }else {
                        gfjTzSj = getFen(one.getGufengji1changetime(),date);
                    }
                    one.setGufengji1changetime(date);
                }
                if (!gufengji2State.equals(one.getGufengji2())) {
                    one.setGufengji2changetime(date);
                }
//                if (!jiaobanjiState.equals(one.getJinshuibeng())) {
//                    one.setJiaobanjichangetime(date);
//                }
                if (!huiliubengState.equals(one.getHuiliubeng())) {
                    if("1".equals(one.getHuiliubeng())){
                        hlbYxSj = getFen(one.getHuiliubengchangetime(),date);
                    }else {
                        hlbTzSj = getFen(one.getHuiliubengchangetime(),date);
                    }
                    one.setHuiliubengchangetime(date);
                }

                one.setChanshuibeng(chanshuibengState);
                one.setFanxibeng(fanxibengState);
                one.setJiaobanji(jiaobanjiState);
                one.setGufengji1(gufengji1State);
                one.setGufengji2(gufengji2State);
                one.setJinshuibeng(jinshuibengState);
                one.setHuiliubeng(huiliubengState);
                one.setChanshuibengstrattime(chanshuibengRuntime);
                one.setChanshuibengendtime(chanshuibengStoptime);
                one.setFanxibengstrattime(fanxibengRuntime);
                one.setFanxibengendtime(fanxibengStoptime);
                one.setGufengjistrattime(gufengjiRuntime);
                one.setGufengjiendtime(gufengjiStoptime);
                one.setJiaobanjistrattime(jiaobanRuntime);
                one.setJiaobanjiendtime(jiaobanStoptime);
                one.setHuiliubengstarttime(huiliubengRuntime);
                one.setHuiliubengendtime(huiliubengStoptime);
                // one.setState("0");
                one.setCreateTime(date);
                linedMapper.updateByPrimaryKeySelective(one);
                checkAlert(one,csbYxSj,csbTzSj,fxbYxSj,fxbTzSj,gfjYxSj,gfjTzSj,jbjYxSj,jbjTzSj,hlbYxSj,hlbTzSj);
               // System.out.println("更新成功！！！！！！！！！！！！！！！！！！！更新时间：" + one.getCreateTime());
              //  System.out.println(numberBig + "空格================上面是16下面是报文" + jinzhi);
            }
        }
    }


    public void updateLinedState( String numberBig, String jinzhi) {

        LinedState one = null;
        Date date = new Timestamp(System.currentTimeMillis());
        LinedState old = linedStateMapper.getLinedStateByField("number", numberBig.trim());
        if (old == null) {
            LinedState linedState = new LinedState();
            linedState.setTid(UUID.randomUUID().toString());
            linedState.setNumber(numberBig);
            linedState.setCreatetime(date);
            linedState.setUpdatetime(date);
            linedState.setState("0");
            linedState.setBinding("0");
            linedStateMapper.insertSelective(linedState);
            one = linedState;
        }else{
            one = old;
        }
        if (numberBig != null&&!"".equals(numberBig)) {
            // one = linedStateMapper.getLinedStateByField("number", numberBig);
            if (one != null) {
                String chanshuibengState = hexToDecOfString(jinzhi.substring(12, 14) + jinzhi.substring(15, 17));
                String fanxibengState = hexToDecOfString(jinzhi.substring(18, 20) + jinzhi.substring(21, 23));
                String jiaobanjiState = hexToDecOfString(jinzhi.substring(24, 26) + jinzhi.substring(27, 29));
                String gufengji1State = hexToDecOfString(jinzhi.substring(30, 32) + jinzhi.substring(33, 35));
                String gufengji2State = hexToDecOfString(jinzhi.substring(36, 38) + jinzhi.substring(39, 41));
                String jinshuibengState = hexToDecOfString(jinzhi.substring(42, 44) + jinzhi.substring(45, 47));
                String huiliubengState = hexToDecOfString(jinzhi.substring(48, 50) + jinzhi.substring(51, 53));
                int chanshuibengRuntime = hexToDec(jinzhi.substring(54, 56) + jinzhi.substring(57, 59));
                int chanshuibengStoptime = hexToDec(jinzhi.substring(60, 62) + jinzhi.substring(63, 65));
                int fanxibengRuntime = hexToDec(jinzhi.substring(66, 68) + jinzhi.substring(69, 71));
                int fanxibengStoptime = hexToDec(jinzhi.substring(72, 74) + jinzhi.substring(75, 77));
                int gufengjiRuntime = hexToDec(jinzhi.substring(78, 80) + jinzhi.substring(81, 83));
                int gufengjiStoptime = hexToDec(jinzhi.substring(84, 86) + jinzhi.substring(87, 89));
                int jiaobanRuntime = hexToDec(jinzhi.substring(90, 92) + jinzhi.substring(93, 95));
                int jiaobanStoptime = hexToDec(jinzhi.substring(96, 98) + jinzhi.substring(99, 101));
                int huiliubengRuntime = hexToDec(jinzhi.substring(102, 104) + jinzhi.substring(105, 107));
                int huiliubengStoptime = hexToDec(jinzhi.substring(108, 110) + jinzhi.substring(111, 113));

                if (!chanshuibengState.equals(one.getChanshuibeng())) {
                    one.setChanshuibengchangetime(date);
                }
                if (!(fanxibengState).equals(one.getFanxibeng())) {
                    one.setFanxibengchangetime(date);
                }
                if (!(jiaobanjiState).equals(one.getJiaobanji())) {
                    one.setJiaobanjichangetime(date);
                }
                if (!(gufengji1State).equals(one.getGufengji1())) {
                    one.setGufengji1changetime(date);
                }
                if (!(gufengji2State).equals(one.getGufengji2())) {
                    one.setGufengji2changetime(date);
                }
                if (!(jiaobanjiState).equals(one.getJinshuibeng())) {
                    one.setJiaobanjichangetime(date);
                }
                if (!(huiliubengState).equals(one.getHuiliubeng())) {
                    one.setHuiliubengchangetime(date);
                }
                one.setChanshuibeng(chanshuibengState);
                one.setFanxibeng(fanxibengState);
                one.setJiaobanji(jiaobanjiState);
                one.setGufengji1(gufengji1State);
                one.setGufengji2(gufengji2State);
                one.setJinshuibeng(jinshuibengState);
                one.setHuiliubeng(huiliubengState);
                one.setChanshuibengstrattime(chanshuibengRuntime);
                one.setChanshuibengendtime(chanshuibengStoptime);
                one.setFanxibengstrattime(fanxibengRuntime);
                one.setFanxibengendtime(fanxibengStoptime);
                one.setGufengjistrattime(gufengjiRuntime);
                one.setGufengjiendtime(gufengjiStoptime);
                one.setJiaobanjistrattime(jiaobanRuntime);
                one.setJiaobanjiendtime(jiaobanStoptime);
                one.setHuiliubengstarttime(huiliubengRuntime);
                one.setHuiliubengendtime(huiliubengStoptime);
                one.setUpdatetime(date);
                linedStateMapper.updateByPrimaryKeySelective(one);
            }
        }
    }

    public  void   updateAlterValue(String number,String jinzhi){
        AlertValue alertValue = alertValueMapper.selectByPrimaryKey(number);
        Boolean insert = false;
        int chanshuibengRuntime = hexToDec(jinzhi.substring(54, 56) + jinzhi.substring(57, 59));
        int chanshuibengStoptime = hexToDec(jinzhi.substring(60, 62) + jinzhi.substring(63, 65));
        int fanxibengRuntime = hexToDec(jinzhi.substring(66, 68) + jinzhi.substring(69, 71));
        int fanxibengStoptime = hexToDec(jinzhi.substring(72, 74) + jinzhi.substring(75, 77));
        int gufengjiRuntime = hexToDec(jinzhi.substring(78, 80) + jinzhi.substring(81, 83));
        int gufengjiStoptime = hexToDec(jinzhi.substring(84, 86) + jinzhi.substring(87, 89));
        int jiaobanRuntime = hexToDec(jinzhi.substring(90, 92) + jinzhi.substring(93, 95));
        int jiaobanStoptime = hexToDec(jinzhi.substring(96, 98) + jinzhi.substring(99, 101));
        int huiliubengRuntime = hexToDec(jinzhi.substring(102, 104) + jinzhi.substring(105, 107));
        int huiliubengStoptime = hexToDec(jinzhi.substring(108, 110) + jinzhi.substring(111, 113));
       if(alertValue == null){
           AlertValue alertValue1 = new AlertValue();
           alertValue1.setTid(number);
           alertValue1.setNumber(number);
           alertValue1.setCsbStart(chanshuibengRuntime);
           alertValue1.setCsbEnd(chanshuibengStoptime);
           alertValue1.setFxbStart(fanxibengRuntime);
           alertValue1.setFxbEnd(fanxibengStoptime);
           alertValue1.setGfjStart(gufengjiRuntime);
           alertValue1.setGfjEnd(gufengjiStoptime);
           alertValue1.setJbjStart(jiaobanRuntime);
           alertValue1.setJbjEnd(jiaobanStoptime);
           alertValue1.setHlbStart(huiliubengRuntime);
           alertValue1.setHlbEnd(huiliubengStoptime);
           Lined lined = linedMapper.getByDtu(number);
          if(lined != null){
              alertValue1.setCun(lined.getCun());
              alertValue1.setZhen(lined.getZhen());
          }
           alertValue = alertValue1;
           alertValueMapper.insert(alertValue);
           return;
       }
           if(alertValue.getCsbStart() != chanshuibengRuntime){
               insert = true;
               alertValue.setCsbStart(chanshuibengRuntime);
           }
           if(alertValue.getCsbEnd() != chanshuibengStoptime){
               insert = true;
               alertValue.setCsbEnd(chanshuibengStoptime);
           }
           if(alertValue.getFxbStart() != fanxibengRuntime){
               insert = true;
               alertValue.setFxbStart(fanxibengRuntime);
           }
           if(alertValue.getFxbEnd() != fanxibengStoptime){
               insert = true;
               alertValue.setFxbEnd(fanxibengStoptime);
           }
           if(alertValue.getGfjStart() != gufengjiRuntime){
               insert = true;
               alertValue.setGfjStart(gufengjiRuntime);
           }
           if(alertValue.getGfjEnd() != gufengjiStoptime){
               insert = true;
               alertValue.setGfjEnd(gufengjiStoptime);
           }
           if(alertValue.getJbjStart() != jiaobanRuntime){
               insert = true;
               alertValue.setJbjStart(jiaobanRuntime);
           }
           if(alertValue.getJbjEnd() != jiaobanStoptime){
               insert = true;
               alertValue.setJbjEnd(jiaobanStoptime);
           }
           if(alertValue.getHlbStart() != jiaobanRuntime){
               insert = true;
               alertValue.setJbjStart(jiaobanRuntime);
           }
           if(alertValue.getHlbEnd() != huiliubengStoptime){
               insert = true;
               alertValue.setHlbEnd(huiliubengStoptime);
           }

       if(insert){
           if(alertValue.getCun() == null){
              Lined lined = linedMapper.getByDtu(number) ;
              if(lined != null ){
                  alertValue.setZhen(lined.getZhen());
                  alertValue.setCun(lined.getCun());
              }
           }
           alertValueMapper.updateByPrimaryKeySelective(alertValue);
       }
    }


    //return 0||1 0为无异常或异常已处理 1为有新异常或旧异常未处理
    public int addAlert(Lined lined, String type, boolean flag) {
        int result = 0;
        Alert alert = new Alert();
        alert.setTid(UUID.randomUUID().toString());
        alert.setNumber(lined.getNumber());
         if(type.endsWith("泵")|| type.endsWith("机")){
           alert.setType(type+"过载");
           alert.setReason(type + "过载报警");
       }else {
           alert.setType(type.substring(0, type.length() - 2));
           alert.setReason(type + "时间过长");
       }
        alert.setState("0");
        List<Alert> alertList = alertMapper.getAlertListByClassify(alert,null,null);
        int i = alertList.size();
        //如果该编号有异常就遍历该编号的异常
        if (!alertList.isEmpty()) {
            for(Alert alert1:alertList){
                //如果异常列表中已有新异常
                if (alert.getType().equals(alert1.getType()) && alert.getReason().equals(alert1.getReason())) {
                    //如果要添加的异常已经不存在就将异常状态改为已处理
                    if (!flag) {
                        alert1.setState("1");
                        alert1.setIsShow(0);//改为不显示该异常
                        alertMapper.updateByPrimaryKeySelective(alert1);
                    }else {
                        result = 1;
                    }
                }else {//记录要添加的异常是否在异常列表中
                    i--;
                }
                //进入该函数说明连线成功，该异常状态改为已处理
                if("DTU异常".equals(alert1.getType()) && "断线时间过长，获取不到DTU数据".equals(alert1.getReason())){
                    alert1.setState("1");
                    alert1.setIsShow(0);//改为不显示该异常
                    alertMapper.updateByPrimaryKeySelective(alert1);
                }
            }
        }
        //如果有新异常并且异常列表中没有该异常就新增这个异常
        if (flag && i == 0) {
            alert.setTime(new Timestamp(System.currentTimeMillis()));
            alert.setState("0");
            alert.setIsShow(1);
            alert.setJingdu(lined.getZhen());
            alert.setWeidu(lined.getCun());
            alertMapper.insertSelective(alert);
            System.out.print(lined.getNumber() + type + "时间过长");
            result = 1;
        }
        return  result;
    }

     public void checkAlert(Lined lined,Integer csbKsSj,Integer csbTzsj,Integer fxbKsSj,Integer fxbTzsj,Integer gfjKssj,Integer gfjTzSj,Integer jbjKsSj,Integer jbjTzSj,Integer hlbKsSj,Integer hlbTzSj) {
        System.out.print(lined.getNumber()+"异常检测中。。。。。。。。。。。。");
        addAlert(lined, "产水泵运行", csbKsSj == null ? false :csbKsSj > lined.getChanshuibengstrattime()+1);

         addAlert(lined, "产水泵停止", csbTzsj == null ? false : csbTzsj > lined.getChanshuibengendtime()+1 );

        addAlert(lined, "反洗泵运行", fxbKsSj == null ? false :fxbKsSj > lined.getFanxibengstrattime()+1);

         addAlert(lined, "反洗泵停止", fxbTzsj == null ? false : fxbTzsj > lined.getFanxibengendtime()+1);

        addAlert(lined, "回流泵运行", hlbKsSj == null ? false : hlbKsSj > lined.getHuiliubengstarttime()+1);

         addAlert(lined, "回流泵停止", hlbTzSj == null ?false : hlbTzSj >lined.getHuiliubengendtime()+1);

         addAlert(lined, "搅拌机运行", jbjKsSj == null ? false :jbjKsSj> lined.getJiaobanjistrattime()+1);

         addAlert(lined, "搅拌机停止", jbjTzSj == null ? false:jbjTzSj > lined.getJiaobanjiendtime()+1);

         addAlert(lined, "鼓风机运行", gfjKssj == null ? false :gfjKssj > lined.getGufengjistrattime()+1);

         addAlert(lined, "鼓风机停止", gfjTzSj == null ? false : gfjTzSj>lined.getGufengjiendtime()+1);

        int sum = addAlert(lined,"产水泵","2".equals(lined.getChanshuibeng()));

        sum  = sum + addAlert(lined,"反洗泵","2".equals(lined.getFanxibeng()));

        sum  = sum + addAlert(lined,"鼓风机","2".equals(lined.getGufengji1()));

        sum  = sum + addAlert(lined,"搅拌机","2".equals(lined.getJiaobanji()));

        sum  = sum + addAlert(lined,"回流泵","2".equals(lined.getHuiliubeng()));

        if(sum > 0){
            if(!"1".equals(lined.getState())){
                linedMapper.updateStateByNumber("1",lined.getNumber());
                linedStateMapper.updateStateByNumber("1",lined.getNumber());
                System.out.print(lined.getNumber()+"发生异常"+"\n");
            }
        }else {
            if(!"0".equals(lined.getState())){
                linedMapper.updateStateByNumber("0",lined.getNumber());
                linedStateMapper.updateStateByNumber("0",lined.getNumber());
                System.out.print(lined.getNumber()+"正常执行"+"\n");
            }
        }
    }

    public static Integer getFen(Date satrtTime,Date endTime){
        if(satrtTime == null){
            return  null;
        }
        long cha = endTime.getTime() - satrtTime.getTime();
        return  (int) cha / (1000*60);
    }

    //十六进制转十进制
    public static int hexToDec(String hex) {                //转化为十六进制
        int decValue = 0;
        for (int i = 0; i < hex.length(); i++) {                   //字符串的位置从0位开始
            char hexChar = hex.charAt(i);                           //获取十六进制各个位置的内容
            decValue = decValue * 16 + hexCharToDec(hexChar);     //计算转化为十进制的值
        }
        return decValue;
    }


    //十六进制装十进制
    public static String hexToDecOfString(String hex) {                //转化为十六进制
        int decValue = 0;
        for (int i = 0; i < hex.length(); i++) {                   //字符串的位置从0位开始
            char hexChar = hex.charAt(i);                           //获取十六进制各个位置的内容
            decValue = decValue * 16 + hexCharToDec(hexChar);     //计算转化为十进制的值
        }
        return String.valueOf(decValue);
    }

    public static int hexCharToDec(char ch) {             //将A~F的转化为相应的数值10~15
        if (ch >= 'A' && ch <= 'F')
            return 10 + ch - 'A';
        else
            return ch - '0';
    }

    //代表一个连接，负责信息的接收与转发
    private class User implements Runnable {

        private boolean isRun = true;

        private Socket client;
        InputStream inputStream;
        OutputStream outputStream;
        DataOutputStream dataOutputStream =null ;
        String numberBig = "";

        public Socket getClient() {
            return client;
        }

        public void setClient(Socket client) {
            this.client = client;
        }

        public User(Socket client) {

            try {

                this.client = client;
                this.inputStream = client.getInputStream();
                this.outputStream = client.getOutputStream();
//                this.dataOutputStream= new DataOutputStream(outputStream);

//                is=new DataInputStream(client.getInputStream());
//                os=new DataOutputStream(client.getOutputStream());
                isRun = true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                isRun = false;
                CloseUtil.closeAll(inputStream, outputStream);
            }
//            try {
//                name=is.readUTF();
//                System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+name);
//              //  this.sendOther(new String("欢迎"+name+"进入聊天室"),true);
//                this.send(new String("OK"));
//            }catch (Exception e) {
//                e.printStackTrace();
//            }
        }

        @Override
        public void run() {

            // TODO Auto-generated method stub
            while (isRun) {
                try {
//                this.sendOther(this.revice(),false);
                    System.out.println("=================================轮询等待Dtux消息=============================");
                    byte[] bytes = new byte[1024];
                    inputStream.read(bytes);
                    String string = new String(bytes);
                    System.out.println(string);
//                    dataOutputStream.write(inputStream.read(bytes));
//                    dataOutputStream.flush();

                    if (!string.contains("DTU")) {
                        if (string.length() > 23 && string.contains("WZSNWV1")) {
                            numberBig = string.substring(3, 19);
                           //System.out.println(numberBig + "字符串!!!!!!!!!!!!!!!!!!");
                        } else {
                            String jinzhi = bytesToHexString(bytes);
                            jinzhi = jinzhi.substring(0, 119);
                          //  System.out.println("外层~~~~~~~~~~~~~"+jinzhi);
                            updateAlterValue(numberBig,jinzhi);
                            updateLinedState( numberBig, jinzhi);
                            updateLined(numberBig, jinzhi);
                        }
                    }


                    //    System.out.println(string+numberBig);
//                    String number = null;
//                    if(string.indexOf("DTU")==-1){
//
//
//
//                    if(string.length()>23&&string.indexOf("WZSNWV1")!=-1){
//                        number = string.substring(3,19);
//                        System.out.println(number+"字符串");
//                        numberBig = number;
//                        List old = linedMapper.getLinedByNumber(number);
//                        if(old!=null&&old.size()==0){
//                            Lined lined = new Lined();
//
//                            System.out.println("新增："+number+"!!!!!!!!!!!!!!!!!");
//
//                            lined.setNumber(number);
//
//                            lined.setTid(UUID.randomUUID().toString());
//                            linedMapper.insertSelective(lined);
//
//                        }
//
//
//
//                    } else{
//
//                            String jinzhi =     bytesToHexString(bytes);
//                            jinzhi = jinzhi.substring(0,119);
//                            if(numberBig!=null){
//                                Lined one = linedMapper.getByDtu(numberBig);
//                                if(one!=null){
//                                    String chanshuibengState = jinzhi.substring(12,14)+jinzhi.substring(15,17);
//                                    String fanxibengState = jinzhi.substring(18,20)+jinzhi.substring(21,23);
//                                    String jiaobanjiState = jinzhi.substring(24,26)+jinzhi.substring(27,29);
//                                    String gufengji1State = jinzhi.substring(30,32)+jinzhi.substring(33,35);
//                                    String gufengji2State = jinzhi.substring(36,38)+jinzhi.substring(39,41);
//                                    String jinshuibengState = jinzhi.substring(42,44)+jinzhi.substring(45,47);
//                                    String huiliubengState = jinzhi.substring(48,50)+jinzhi.substring(51,53);
//
//                                    String chanshuibengRuntime = jinzhi.substring(54,56)+jinzhi.substring(57,59);
//                                    String chanshuibengStoptime = jinzhi.substring(60,62)+jinzhi.substring(63,65);
//                                    String fanxibengRuntime = jinzhi.substring(66,68)+jinzhi.substring(69,71);
//                                    String fanxibengStoptime = jinzhi.substring(72,74)+jinzhi.substring(97,99);
//                                    String gufengjiRuntime = jinzhi.substring(78,80)+jinzhi.substring(81,83);
//                                    String gufengjiStoptime = jinzhi.substring(84,86)+jinzhi.substring(87,89);
//                                    String jiaobanRuntime = jinzhi.substring(90,92)+jinzhi.substring(93,95);
//                                    String jiaobanStoptime = jinzhi.substring(96,98)+jinzhi.substring(99,101);
//                                    String huiliubengRuntime = jinzhi.substring(102,104)+jinzhi.substring(105,107);
//                                    String huiliubengStoptime = jinzhi.substring(108,110)+jinzhi.substring(111,113);
//
//                                    one.setChanshuibeng(chanshuibengState);
//                                    one.setFanxibeng(fanxibengState);
//                                    one.setJiaobanji(jiaobanjiState);
//                                    one.setGufengji1(gufengji1State);
//                                    one.setGufengji2(gufengji2State);
//                                    one.setJinshuibeng(jinshuibengState);
//                                    one.setHuiliubeng(huiliubengState);
//                                    System.out.println("原来的时间："+one.getCreateTime());
//                                    one.setCreateTime(new Timestamp(System.currentTimeMillis()));
//                                    linedMapper.updateByPrimaryKeySelective(one);
//                                    System.out.println("更新成功！！！！！！！！！！！！！！！！！！！更新时间："+one.getCreateTime());
//                                    System.out.println(numberBig+"空格================上面是16下面是报文"+jinzhi);
//                                }
//
//                            }
//
//                        }
//
//                    }

                    //向客户端发送消息
                    outputStream.write("iiiok".getBytes());
                    System.out.println("OK" + "正常输入输出");
                } catch (Exception e) {
                    e.printStackTrace();
                    isRun = false;
                    CloseUtil.closeAll(inputStream, outputStream);
                    System.out.println("断掉了！！！！！！！！！！！！！");
                }
            }
            CloseUtil.closeAll(inputStream, outputStream, client);
        }
    }

    public static String bytesToHexString(byte[] src) {
        StringBuffer sb = new StringBuffer("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                sb.append(0);
            }
            sb.append(hv);
            if (i != src.length - 1) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }


}